﻿//创建时间: 2010-11-17
//创建作者: 李晓忠
//功能说明: 文件操作通用类         
//最后修改: 2010-11-17 李城  添加 WriteFile  ReadFile
//最后修改: 2010-12-2 李 晓忠  添加 CheckPathAndCreate
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Text.RegularExpressions;

namespace TRPOP.Common
{
    /// <summary>
    /// 通用的文件操作类
    /// </summary>
    public class FileUtil
    {
        /// <summary>
        /// 整个文件操作的 Encoding 类型
        /// </summary>
        private static System.Text.Encoding oEncoding = System.Text.Encoding.UTF8;//System.Text.Encoding.GetEncoding("gb2312");
        private static object objLock = new object();

        /// <summary>
        ///  获取目录下文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="extName">扩展名</param>
        /// <returns></returns>
        public static JavaScriptObject getJsonFileList(string path,string extName)
        {
            JavaScriptObject fileJson = new JavaScriptObject();
            JavaScriptObject flist = new JavaScriptObject();
            JavaScriptObject dirlist = new JavaScriptObject();
            JavaScriptObject objfile = null;
            try
            {
                string[] dir = Directory.GetDirectories(path); //文件夹列表   
                DirectoryInfo fdir = new DirectoryInfo(path);
                FileInfo[] file = fdir.GetFiles();

                //FileInfo[] file = Directory.GetFiles(path); //文件列表   
                if (file.Length != 0 || dir.Length != 0) //当前目录文件或文件夹不为空                   
                {
                    foreach (FileInfo f in file) //显示当前目录所有文件   
                    {
                        if (extName.ToLower().IndexOf("|" + f.Extension.ToLower() + "|") >= 0)
                        {
                            objfile = new JavaScriptObject();
                            objfile.Add("name", f.Name);
                            objfile.Add("extname", f.FullName.Substring(f.FullName.LastIndexOf(".") + 1).ToLower());
                            objfile.Add("size", f.Length);
                            flist.Add(f.Name, objfile);
                        }
                    }
                    fileJson.Add("filelist", flist);
                    foreach (string d in dir)
                    {
                        string shordir = d.Replace(path, "").Replace("\\","") ;
                        dirlist.Add(shordir, shordir);
                    }
                    fileJson.Add("dirlist", dirlist);
                }
            }
            catch (Exception error)
            {
                fileJson.Add("filelist", flist);
                fileJson.Add("dirlist", dirlist);
                fileJson.Add("err",error.Message);
            }
            return fileJson;
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="Path">文件详细路径</param>
        /// <returns></returns>
        public static string ReadFile(string Path)
        {
            if (System.IO.File.Exists(Path))
            {
                lock (objLock)
                {
                    string strReturn = string.Empty;
                    StreamReader oSR = new StreamReader(Path, oEncoding);
                    oSR.BaseStream.Position = 0;
                    strReturn = oSR.ReadToEnd();
                    oSR.Close();
                    oSR.Dispose();
                    return strReturn;
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="Strings">文件内容</param>
        public static void WriteFile(string Path, string Strings)
        {

            if (!System.IO.File.Exists(Path))
            {
                lock (objLock)
                {
                    if (!System.IO.Directory.Exists(Path.Substring(0, Path.LastIndexOf("\\"))))
                    {
                        Directory.CreateDirectory(Path.Substring(0, Path.LastIndexOf("\\")));
                    }
                    if (!System.IO.File.Exists(Path))
                    {
                        System.IO.FileStream strR = System.IO.File.Create(Path);
                        strR.Close();
                        strR.Dispose();
                    }
                }
            }
            lock (objLock)
            {
                using (System.IO.StreamWriter strW = new System.IO.StreamWriter(Path, false, oEncoding))
                {
                    strW.WriteLine(Strings);
                    strW.Close();
                }
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="FileUrl">可以带http:// </param>
        /// <param name="Reg">是否正则删除</param>
        /// <param name="FileAdd">_</param>
        public static void DeleteFile(string FileUrl, bool Reg, string FileAdd)
        {
            string strfileRoot = "";
            if (
                (FileUrl.Contains(".") == false)//不包含.
                || (strfileRoot = CommonRegex.GetHttpUrlFile(FileUrl)).IsEmpty()//没有路径
                || (strfileRoot.StartsWith(@"/") == false)//不是以/开头 
                || (strfileRoot.Contains(".") == false)//不包含.
                )
                return;
            string strFilePath = string.Empty;
            try
            {
                strFilePath = Util.GetMapPath(strfileRoot);
            }
            catch {
                return;
            }
            if (File.Exists(strFilePath) == false)
                return;
            DelFile(strFilePath);
            if (Reg == false)
                return;
            #region 删除其他与之相关的页面
            string strDir = strFilePath.Remove(strFilePath.LastIndexOf(@"\"));
            if (System.IO.Directory.Exists(strDir) == false)
                return;
            DirectoryInfo fdir = new DirectoryInfo(strDir);
            FileInfo[] file = fdir.GetFiles();
            if (file.Length <= 0)
                return;
            string strfile = strFilePath.Substring(strFilePath.LastIndexOf(@"\") + 1);
            string strfileRegex = strfile.Remove(strfile.LastIndexOf(".")) + "[" + FileAdd + "]" + @"[\d]*[.]" + strfile.Substring(strfile.LastIndexOf(".") + 1);
            Regex reg = new Regex(strfileRegex, RegexOptions.IgnoreCase);
            foreach (FileInfo f in file) //当前目录的所有文件   
            {
                Match match = reg.Match(f.Name);
                if (match.Success)
                {
                    f.Delete();
                }
            }
            #endregion
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="strPhysic"></param>
        public static void DelFile(string strPhysic)
        {
            File.Delete(strPhysic);
        }

        /// <summary>
       /// 检查目录是否存在
       /// </summary>
       /// <param name="path">目录</param>
       /// <param name="create">是否创建</param>
       /// <returns></returns>
        public static bool CheckPathAndCreate(string path,bool create)
        {
            bool result = true;
            try
            {
                if (!System.IO.Directory.Exists(path))
                {
                    result = false;
                    if (create)
                    {
                        Directory.CreateDirectory(path);
                        result = true;
                    }
                }
            }
            catch
            {
                result = false;
            }
            return result;
        }
        /// <summary>
        /// 文件是否存在 
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool IsExist(string path)
        {
            return System.IO.File.Exists(path);
        }

        /// <summary>
        ///文件复制
        /// </summary>
        /// <param name="sourcePath">源文件目录</param>
        /// <param name="targetPath">目标文件目录</param>
        /// <param name="isrewrite">true=覆盖已存在的同名文件,falss= 不覆盖也不copy</param>
        /// <returns></returns>
        public static bool CopyFile(string sourcePath, string targetPath, bool isrewrite)
        {
            bool result = true;
            try
            {
                if (!System.IO.Directory.Exists(targetPath.Substring(0, targetPath.LastIndexOf("\\"))))
                {
                    Directory.CreateDirectory(targetPath.Substring(0, targetPath.LastIndexOf("\\")));
                }
                if (isrewrite)
                {
                    if (System.IO.File.Exists(targetPath))
                    {
                        System.IO.File.Delete(targetPath);
                    }
                    System.IO.File.Copy(sourcePath, targetPath, isrewrite);
                }
                else
                {
                    if (!System.IO.File.Exists(targetPath))
                    {
                        System.IO.File.Copy(sourcePath, targetPath, isrewrite);
                    }
                }
                
            }
            catch (Exception e)
            {
                result = false;
                throw new Exception(e.Message);
            }
            return result;
        }
        
        /// <summary>
        /// 删除指定目录及其所有子目录
        /// </summary>
        /// <param name="directoryPath"></param>
        public static void DeleteDirectory(string directoryPath)
        {
            if (IsExistDirectory(directoryPath))
            {
                Directory.Delete(directoryPath, true);
            }
        }

        /// <summary>
        /// 检测指定目录是否存在
        /// </summary>
        /// <param name="directoryPath"></param>
        /// <returns></returns>
        public static bool IsExistDirectory(string directoryPath)
        {
            return Directory.Exists(directoryPath);
        }
    }
}
